/**
 * 主题应用工具函数
 * 用于将主题色应用到页面的所有相关元素
 */

/**
 * 应用主题色到所有相关元素
 * @param {string} theme - 主题色值
 * @param {string} cssVarPrefix - CSS变量前缀
 */
export function applyThemeToAllElements(theme, cssVarPrefix = '--app') {
    const rgb = hexToRgb(theme)
    
    // 1. 设置CSS变量
    const root = document.documentElement
    root.style.setProperty(`${cssVarPrefix}-bg-color`, theme)
    root.style.setProperty(`${cssVarPrefix}-bg-color-rgb`, rgb)
    root.style.setProperty('--demo-bg-color', theme)
    root.style.setProperty('--demo-bg-color-rgb', rgb)
    
    // 2. 设置基础元素背景色
    document.documentElement.style.backgroundColor = theme
    document.body.style.backgroundColor = theme
    
    // 3. 设置应用容器背景色
    const appElement = document.getElementById('app')
    if (appElement) {
        appElement.style.backgroundColor = theme
    }
    
    // 4. 定义需要应用主题色的选择器
    const selectors = {
        // 页面容器
        pages: '.hooks-demo, .home, .about, .canves, .element-css, .home-page, .system-page, .page-content, .content-area, .main-content, [class*="page"], [class*="view"]',
        
        // 卡片组件
        cards: '.el-card, .my-el-card, .card, [class*="card"], [class*="Card"]',
        
        // 表格组件
        tables: '.el-table, .el-table th, .el-table td, table, th, td, [class*="table"], [class*="Table"]',
        
        // 对话框组件
        dialogs: '.el-dialog, .el-drawer, [class*="dialog"], [class*="Dialog"], [class*="drawer"], [class*="Drawer"]',
        
        // 下拉菜单组件
        dropdowns: '.el-dropdown-menu, .el-select-dropdown, .el-date-picker, .el-time-picker, .el-cascader__dropdown, [class*="dropdown"], [class*="Dropdown"]',
        
        // 弹出框组件
        popovers: '.el-popover, .el-popconfirm, .el-tooltip__popper, [class*="popover"], [class*="Popover"]',
        
        // 消息提示组件
        messages: '.el-message, .el-notification, [class*="message"], [class*="Message"], [class*="notification"], [class*="Notification"]',
        
        // 加载组件
        loading: '.el-loading-mask, [class*="loading"], [class*="Loading"]',
        
        // 标签组件
        tags: '.el-tag, [class*="tag"], [class*="Tag"]',
        
        // 分割线组件
        dividers: '.el-divider, [class*="divider"], [class*="Divider"]',
        
        // 回到顶部组件
        backtop: '.el-backtop, [class*="backtop"], [class*="Backtop"]',
        
        // 虚拟滚动组件
        scrollbars: '.el-virtual-scrollbar, [class*="scrollbar"], [class*="Scrollbar"]',
        
        // 折叠面板组件
        collapse: '.el-collapse-item__header, .el-collapse-item__content, .el-collapse-item__wrap, [class*="collapse"], [class*="Collapse"]',
        
        // 描述列表组件
        descriptions: '.el-descriptions__body, [class*="descriptions"], [class*="Descriptions"]',
        
        // 标签页组件
        tabs: '.el-tabs__content, [class*="tabs"], [class*="Tabs"]',
        
        // 步骤条组件
        steps: '.el-steps, [class*="steps"], [class*="Steps"]',
        
        // 时间线组件
        timeline: '.el-timeline, [class*="timeline"], [class*="Timeline"]',
        
        // 轮播图组件
        carousel: '.el-carousel, [class*="carousel"], [class*="Carousel"]',
        
        // 空状态组件
        empty: '.el-empty, [class*="empty"], [class*="Empty"]',
        
        // 骨架屏组件
        skeleton: '.el-skeleton, [class*="skeleton"], [class*="Skeleton"]',
        
        // 结果组件
        result: '.el-result, [class*="result"], [class*="Result"]',
        
        // 统计数值组件
        statistic: '.el-statistic, [class*="statistic"], [class*="Statistic"]',
        
        // 头像组件
        avatar: '.el-avatar, [class*="avatar"], [class*="Avatar"]',
        
        // 图片组件
        image: '.el-image, [class*="image"], [class*="Image"]',
        
        // 链接组件
        link: '.el-link, [class*="link"], [class*="Link"]',
        
        // 无限滚动组件
        infinite: '.el-infinite-scroll, [class*="infinite"], [class*="Infinite"]',
        
        // 表单组件
        forms: '.el-form, .el-form-item, [class*="form"], [class*="Form"]',
        
        // 输入框组件
        inputs: '.el-input__inner, input[type="text"], input[type="password"], input[type="email"], input[type="number"], input[type="search"], input[type="tel"], input[type="url"], textarea, select, [class*="input"], [class*="Input"]',
        
        // 按钮组件
        buttons: '.el-button, .my-el-button, button, [class*="button"], [class*="Button"]',
        
        // 导航组件
        navigation: 'nav, [class*="nav"], [class*="Nav"], [class*="menu"], [class*="Menu"]',
        
        // 侧边栏组件
        sidebar: '.sidebar, [class*="sidebar"], [class*="Sidebar"], [class*="aside"], [class*="Aside"]',
        
        // 头部组件
        header: '.header, [class*="header"], [class*="Header"], [class*="top"], [class*="Top"]',
        
        // 底部组件
        footer: '.footer, [class*="footer"], [class*="Footer"], [class*="bottom"], [class*="Bottom"]',
        
        // 内容区域组件
        content: '.content, [class*="content"], [class*="Content"], .main, [class*="main"], [class*="Main"]',
        
        // 容器组件
        container: '.container, [class*="container"], [class*="Container"], .wrapper, [class*="wrapper"], [class*="Wrapper"]'
    }
    
    // 5. 应用主题色到所有选择器
    Object.entries(selectors).forEach(([key, selector]) => {
        try {
            const elements = document.querySelectorAll(selector)
            elements.forEach(element => {
                if (element && element.style) {
                    // 根据组件类型设置不同的背景色
                    switch (key) {
                        case 'loading':
                            element.style.backgroundColor = `rgba(${rgb}, 0.8)`
                            break
                        case 'tags':
                            element.style.backgroundColor = `rgba(${rgb}, 0.1)`
                            element.style.borderColor = `rgba(${rgb}, 0.2)`
                            break
                        case 'dividers':
                            element.style.backgroundColor = `rgba(${rgb}, 0.2)`
                            break
                        case 'backtop':
                            element.style.backgroundColor = `rgba(${rgb}, 0.8)`
                            break
                        case 'scrollbars':
                            element.style.backgroundColor = `rgba(${rgb}, 0.1)`
                            break
                        case 'collapse':
                            if (element.classList.contains('el-collapse-item__header')) {
                                element.style.backgroundColor = `rgba(${rgb}, 0.05)`
                            } else {
                                element.style.backgroundColor = theme
                            }
                            break
                        case 'inputs':
                            element.style.backgroundColor = `rgba(${rgb}, 0.05)`
                            element.style.borderColor = `rgba(${rgb}, 0.2)`
                            break
                        case 'navigation':
                        case 'sidebar':
                        case 'header':
                        case 'footer':
                            element.style.backgroundColor = `rgba(${rgb}, 0.9)`
                            break
                        default:
                            element.style.backgroundColor = theme
                    }
                }
            })
        } catch (error) {
            console.warn(`应用主题色到选择器 ${selector} 时出错:`, error)
        }
    })
    
    // 6. 特殊处理：动态创建的元素
    setTimeout(() => {
        // 延迟执行，确保动态元素已创建
        applyThemeToAllElements(theme, cssVarPrefix)
    }, 100)
    
    console.log(`主题已应用到所有元素: ${theme}`)
}

/**
 * 十六进制转RGB
 * @param {string} hex - 十六进制颜色值
 * @returns {string} RGB字符串
 */
function hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    if (result) {
        const r = parseInt(result[1], 16)
        const g = parseInt(result[2], 16)
        const b = parseInt(result[3], 16)
        return `${r}, ${g}, ${b}`
    }
    return '255, 255, 255'
}

/**
 * 获取对比色
 * @param {string} hex - 十六进制颜色值
 * @returns {string} 对比色值
 */
export function getContrastColor(hex) {
    const rgb = hexToRgb(hex).split(', ').map(Number)
    const brightness = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000
    return brightness > 128 ? '#000000' : '#ffffff'
}

/**
 * 监听DOM变化，自动应用主题色到新元素
 * @param {string} theme - 主题色值
 * @param {string} cssVarPrefix - CSS变量前缀
 */
export function watchDOMChanges(theme, cssVarPrefix = '--app') {
    const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            if (mutation.type === 'childList') {
                mutation.addedNodes.forEach((node) => {
                    if (node.nodeType === Node.ELEMENT_NODE) {
                        // 新添加的元素，应用主题色
                        applyThemeToElement(node, theme, cssVarPrefix)
                    }
                })
            }
        })
    })
    
    observer.observe(document.body, {
        childList: true,
        subtree: true
    })
    
    return observer
}

/**
 * 应用主题色到单个元素
 * @param {Element} element - 目标元素
 * @param {string} theme - 主题色值
 * @param {string} cssVarPrefix - CSS变量前缀
 */
function applyThemeToElement(element, theme, cssVarPrefix) {
    if (!element || !element.style) return
    
    const rgb = hexToRgb(theme)
    
    // 检查元素类型并应用相应的主题色
    if (element.classList.contains('el-card') || element.classList.contains('my-el-card')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-table') || element.tagName === 'TABLE') {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-dialog') || element.classList.contains('el-drawer')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-dropdown-menu') || element.classList.contains('el-select-dropdown')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-popover') || element.classList.contains('el-tooltip__popper')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-message') || element.classList.contains('el-notification')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-loading-mask')) {
        element.style.backgroundColor = `rgba(${rgb}, 0.8)`
    } else if (element.classList.contains('el-tag')) {
        element.style.backgroundColor = `rgba(${rgb}, 0.1)`
        element.style.borderColor = `rgba(${rgb}, 0.2)`
    } else if (element.classList.contains('el-divider')) {
        element.style.backgroundColor = `rgba(${rgb}, 0.2)`
    } else if (element.classList.contains('el-backtop')) {
        element.style.backgroundColor = `rgba(${rgb}, 0.8)`
    } else if (element.classList.contains('el-virtual-scrollbar')) {
        element.style.backgroundColor = `rgba(${rgb}, 0.1)`
    } else if (element.classList.contains('el-collapse-item__header')) {
        element.style.backgroundColor = `rgba(${rgb}, 0.05)`
    } else if (element.classList.contains('el-collapse-item__content') || element.classList.contains('el-collapse-item__wrap')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-descriptions__body')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-tabs__content')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-steps')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-timeline')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-carousel')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-empty')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-skeleton')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-result')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-statistic')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-avatar')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-image')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-link')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-infinite-scroll')) {
        element.style.backgroundColor = theme
    } else if (element.classList.contains('el-form') || element.classList.contains('el-form-item')) {
        element.style.backgroundColor = 'transparent'
    } else if (element.classList.contains('el-input__inner') || element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || element.tagName === 'SELECT') {
        element.style.backgroundColor = `rgba(${rgb}, 0.05)`
        element.style.borderColor = `rgba(${rgb}, 0.2)`
    } else if (element.classList.contains('el-button') || element.classList.contains('my-el-button') || element.tagName === 'BUTTON') {
        // 按钮保持原有样式，只添加过渡效果
        element.style.transition = 'all 0.3s ease'
    } else if (element.classList.contains('nav') || element.classList.contains('sidebar') || element.classList.contains('header') || element.classList.contains('footer')) {
        element.style.backgroundColor = `rgba(${rgb}, 0.9)`
    } else if (element.classList.contains('content') || element.classList.contains('main') || element.classList.contains('container') || element.classList.contains('wrapper')) {
        element.style.backgroundColor = theme
    }
    
    // 递归处理子元素
    const children = element.children
    for (let i = 0; i < children.length; i++) {
        applyThemeToElement(children[i], theme, cssVarPrefix)
    }
} 